package com.utils.loadManager
{
	import flash.display.Bitmap;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.ByteArray;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	/**
	 * 加载管理器 多线程同时加载
	 * 实现并发和队列加载
	 * @author Mr.Lu
	 */	
	public class LoaderManager
	{
		public static const instance:LoaderManager = new LoaderManager();
		private var _loadList:Array = [];
		private var _nameList:Array = [];
		private var _processCount:uint = 1;
		private var _isLoading:Boolean = false;
		
		private var _loaderObject:LoaderObject;
		private var _loadOverCallBack:Function;
		private var _loaderObjectBox:Vector.<LoaderObject> = new Vector.<LoaderObject>();
		public function LoaderManager()
		{
			if(instance) throw Error('单例不能重复实例化!');
		}
		
		/**
		 * 加载线程管理
		 * @param processCount 同时开启加载线程数量
		 * @param args 加载url或者ByteArray数组
		 */		
		public function loadSource(args:Array,processCount:uint=1):void
		{
			_processCount = processCount;
			if(_processCount == 0) _processCount = 1;
			args.reverse();//将数组倒序
			
			_loadList = _loadList.concat(args);
			
			if(!_isLoading) openLoader();
		}
		
		private function openLoader():void
		{
			_isLoading = true;
			for (var i:int = 0; i < _processCount; i++) 
			{
				var param:* = _loadList.pop();
				if(!param) return;
				
				_loaderObject = freeLoaderObject();
				if(!_loaderObject){
					_loaderObject = new LoaderObject();
					_loaderObjectBox.push(_loaderObject);
				}
				
				if(param is String){
					_loaderObject.loadUrl(param);
				}else if(param is ByteArray){
					_loaderObject.loadBytes(param);
				}
				
				_loaderObject.loaderCallBack = loaderCallBack;
			}
		}
		
		private function freeLoaderObject():LoaderObject
		{
			//trace('加载器个数:' + _loaderObjectBox.length);
			for (var i:int = 0; i < _loaderObjectBox.length; i++) 
			{
				if(_loaderObjectBox[i].freeState){
					return _loaderObjectBox[i];
				}
			}
			return null;
		}
		
		private function loaderCallBack(content:*):void
		{
			if(_loadOverCallBack is Function) _loadOverCallBack(content);
			_loadList.length > 0 ? openLoader() : setTimeout(clearLoaderList,100);
		}		
		
		private function clearLoaderList():void
		{
			for (var i:int = 0; i < _loaderObjectBox.length; i++) 
			{
				if(!_loaderObjectBox[i].freeState) return;
			}
			for (var j:int = 0; j < _loaderObjectBox.length; j++) 
			{
				_loaderObjectBox[j].dispose();
				_loaderObjectBox[j] = null;
			}
			_loaderObjectBox = new Vector.<LoaderObject>();
			_isLoading = false;
		}
		
		
		
		
		
		
		
		
		
		
		public function set loadOverCallBack(value:Function):void
		{
			_loadOverCallBack = value;
		}
		
		
	}
}